#
#===============================================================================
#
#         FILE:  Twitter.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/14/2010 11:50:17 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::Twitter;

use Net::Twitter;

my $nt;

sub register {
    my $self = shift;
    my $dbh = shift;

    my $sth = $dbh->prepare("SELECT * FROM sqlite_master WHERE type='table' AND name=?");
    $sth->bind_param(1, 'twitter_config');
    $sth->execute;

    my $test = $sth->fetch; # rows has nothing unless you do a fetch.
    if( ! $sth->rows ) {
        $dbh->do("CREATE TABLE twitter_config (access_token VARCHAR, access_token_secret VARCHAR, user_id VARCHAR, screen_name VARCHAR, create_date timestamp DEFAULT CURRENT_TIMESTAMP, last_update timestamp);");
        $dbh->do("INSERT INTO twitter_config(access_token, access_token_secret, user_id, screen_name) VALUES (NULL, NULL, NULL, NULL)");
    }
    
    create_nt();

    return ('cmd' => 'twitter', 'pat' => '^!twitter(?:pin)?\s+(.*)');
}

sub create_nt {
    if (!defined $nt) {
        $nt = Net::Twitter->new(
            'traits'                => ['API::RESTv1_1', 'OAuth'],
            'consumer_key'                => 'IKNyuDX6sGdqisbwfWJg',
            'consumer_secret'        => '4hUZaGGCAIaNtStgFpqwY6KM1F4Q6A1KcoKbzvOvYA',
            ssl => 1,
        );
    }
}

sub help {
    my $self = shift;

    return ('Return latest twitter post for given screen name');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;
    my $dbh = $conf{'dbh'};

    create_nt();

    my ($access_token, $access_token_secret, $user_id, $screen_name);

    if( $msgtxt =~ /^!twitterpin\s+(.*)/ ) {
        my $pin = $1;
        $kernel->post($sender => privmsg => $target => "Authorizing...");
        ($access_token, $access_token_secret, $user_id, $screen_name) =
                $nt->request_access_token('verifier'=>$pin);
        if( $access_token && $access_token_secret ) {
            $kernel->post($sender => privmsg => $target => "Authorized");
            my $sth = $dbh->prepare("UPDATE twitter_config SET access_token=?, access_token_secret=?, user_id=?, screen_name=?");
            $sth->bind_param(1, $access_token);
            $sth->bind_param(2, $access_token_secret);
            $sth->bind_param(3, $user_id);
            $sth->bind_param(4, $screen_name);
            if( ! $sth->execute ) {
                $kernel->post($sender => privmsg => $target => "Error executing ".$dbh->errstr);
            }
        }
        else {
            $kernel->post($sender => privmsg => $target => "Error authorizing");
        }
        return;
    }

    my $sth = $dbh->prepare("SELECT access_token, access_token_secret FROM twitter_config");
    $sth->execute;
    ($access_token, $access_token_secret) = $sth->fetchrow_array;

    if( $access_token && $access_token_secret ) {
        $nt->access_token($access_token);
        $nt->access_token_secret($access_token_secret);
    }

    unless( $nt->authorized ) {
        $kernel->post($sender => privmsg => $target => "Authorize this app at ".$nt->get_authorization_url." and enter the pin using !twitterpin");
        return;
    }
    
    $msgtxt =~ /^!twitter\s+(.*)/;

    my $res = $nt->lookup_users({'screen_name' => $1});
    if( ! $res ) {
        $kernel->post($sender => privmsg => $target => "Twitter screen name(s) not found.");
        return;
    }
    foreach my $status (@$res) {
        $kernel->post($sender => privmsg => $target => 
                sprintf("%s :: %s / %s", $status->{'screen_name'},
                    $status->{'status'}{'created_at'}, $status->{'status'}{'text'}));
    }
}

1;
